package com.qf.servlet;

import org.omg.SendingContext.RunTime;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 抽取的公共的Servlet
 */

public class BaseServlet extends HttpServlet {

    //覆盖HttpServlet里面的业务入口方法service


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

      /*  //处理post中文乱码
        request.setCharacterEncoding("utf-8") ;
        //响应的中文乱码
        response.setContentType("text/html;charest=utf-8");*/


        try {
            //获取当前子类的字节码文件对象
            Class clazz = this.getClass();
//            System.out.println(clazz);
            //创建当前类实例
            Object obj = clazz.newInstance();
            //获取地址栏携带的参数:约定格式
            //http://localhost:8080/Maven_Project_02_war/子类的模块的地址?methodName=子类的方法名
            String methodName = request.getParameter("methodName");
//            System.out.println(methodName);
            if(methodName==null){
                //http://localhost:8080/Maven_Project_02_war/ 访问地址 :index.jsp 首页
                //赋值
                methodName = "index" ;
            }

            //调用子类的方法
            Method m = clazz.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class) ;
            //调用子类的方法
            m.invoke(obj,request,response) ;

        } catch (Exception e) {
            e.printStackTrace();//打印在控制台上 错误异常

            //如果执行catch语句,throw 一定会执行一个异常,抛出运行时期异常(统一处理)
           /* throw new RuntimeException("父类解析方法出现问题了...") ;*/
        }


    }

    //定义方法名index
    public void index(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        System.out.println("访问的首页...");
    }
}
